package cn.terminus.service.customer.contractinfo;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.terminus.biz.customer.contractfile.ContractFileManager;
import cn.terminus.biz.customer.contractinfo.ContractInfoManager;
import cn.terminus.biz.customer.contractrentdiscountclause.ContractRentDiscountClauseManager;
import cn.terminus.biz.customer.contractrentincrementalclause.ContractRentIncrementalClauseManager;
import cn.terminus.biz.customer.contractsellbystagesinfo.ContractSellByStagesInfoManager;
import cn.terminus.biz.customer.contractsellclauseinfo.ContractSellClauseInfoManager;
import cn.terminus.biz.customer.contractselldefylatedeliveryinfo.ContractSellDefyLateDeliveryInfoManager;
import cn.terminus.biz.customer.contractselldefyloaninfo.ContractSellDefyLoanInfoManager;
import cn.terminus.biz.customer.contractselldefyoverdueapplicationinfo.ContractSellDefyOverdueApplicationInfoManager;
import cn.terminus.biz.customer.contractselldefypaymentoverdueinfo.ContractSellDefyPaymentOverdueInfoManager;
import cn.terminus.biz.customer.customcontacts.CustomContactsManager;
import cn.terminus.biz.customer.custominfo.CustomInfoManager;
import cn.terminus.biz.customer.custompurposeroom.CustomPurposeRoomManager;
import cn.terminus.client.customer.analysis.param.AnalysisYearParam;
import cn.terminus.client.customer.contractfile.param.ContractFileNewParam;
import cn.terminus.client.customer.contractfile.param.ContractFileQueryParam;
import cn.terminus.client.customer.contractfile.result.ContractFileResult;
import cn.terminus.client.customer.contractfile.service.ContractFileService;
import cn.terminus.client.customer.contractinfo.param.*;
import cn.terminus.client.customer.contractinfo.result.ContractInfoResult;
import cn.terminus.client.customer.contractinfo.result.RentContractInfoDetailResult;
import cn.terminus.client.customer.contractinfo.result.SellContractInfoDetailResult;
import cn.terminus.client.customer.contractinfo.service.ContractInfoService;
import cn.terminus.client.customer.contractrentclause.param.ContractRentClauseNewParam;
import cn.terminus.client.customer.contractrentclause.param.ContractRentClauseQueryParam;
import cn.terminus.client.customer.contractrentclause.result.ContractRentClauseResult;
import cn.terminus.client.customer.contractrentclause.service.ContractRentClauseService;
import cn.terminus.client.customer.contractrentdiscountclause.param.ContractRentDiscountClauseNewParam;
import cn.terminus.client.customer.contractrentdiscountclause.param.ContractRentDiscountClauseQueryParam;
import cn.terminus.client.customer.contractrentdiscountclause.result.ContractRentDiscountClauseResult;
import cn.terminus.client.customer.contractrentdiscountclause.service.ContractRentDiscountClauseService;
import cn.terminus.client.customer.contractrentincrementalclause.param.ContractRentIncrementalClauseNewParam;
import cn.terminus.client.customer.contractrentincrementalclause.param.ContractRentIncrementalClauseQueryParam;
import cn.terminus.client.customer.contractrentincrementalclause.result.ContractRentIncrementalClauseResult;
import cn.terminus.client.customer.contractrentincrementalclause.service.ContractRentIncrementalClauseService;
import cn.terminus.client.customer.contractsellbystagesinfo.param.ContractSellByStagesInfoNewParam;
import cn.terminus.client.customer.contractsellbystagesinfo.param.ContractSellByStagesInfoQueryParam;
import cn.terminus.client.customer.contractsellbystagesinfo.result.ContractSellByStagesInfoResult;
import cn.terminus.client.customer.contractsellbystagesinfo.service.ContractSellByStagesInfoService;
import cn.terminus.client.customer.contractsellclauseinfo.param.ContractSellClauseInfoNewParam;
import cn.terminus.client.customer.contractsellclauseinfo.param.ContractSellClauseInfoQueryParam;
import cn.terminus.client.customer.contractsellclauseinfo.result.ContractSellClauseInfoResult;
import cn.terminus.client.customer.contractsellclauseinfo.service.ContractSellClauseInfoService;
import cn.terminus.client.customer.contractselldefylatedeliveryinfo.param.ContractSellDefyLateDeliveryInfoNewParam;
import cn.terminus.client.customer.contractselldefylatedeliveryinfo.param.ContractSellDefyLateDeliveryInfoQueryParam;
import cn.terminus.client.customer.contractselldefylatedeliveryinfo.result.ContractSellDefyLateDeliveryInfoResult;
import cn.terminus.client.customer.contractselldefylatedeliveryinfo.service.ContractSellDefyLateDeliveryInfoService;
import cn.terminus.client.customer.contractselldefyloaninfo.param.ContractSellDefyLoanInfoNewParam;
import cn.terminus.client.customer.contractselldefyloaninfo.param.ContractSellDefyLoanInfoQueryParam;
import cn.terminus.client.customer.contractselldefyloaninfo.result.ContractSellDefyLoanInfoResult;
import cn.terminus.client.customer.contractselldefyloaninfo.service.ContractSellDefyLoanInfoService;
import cn.terminus.client.customer.contractselldefyoverdueapplicationinfo.param.ContractSellDefyOverdueApplicationInfoNewParam;
import cn.terminus.client.customer.contractselldefyoverdueapplicationinfo.param.ContractSellDefyOverdueApplicationInfoQueryParam;
import cn.terminus.client.customer.contractselldefyoverdueapplicationinfo.result.ContractSellDefyOverdueApplicationInfoResult;
import cn.terminus.client.customer.contractselldefyoverdueapplicationinfo.service.ContractSellDefyOverdueApplicationInfoService;
import cn.terminus.client.customer.contractselldefypaymentoverdueinfo.param.ContractSellDefyPaymentOverdueInfoNewParam;
import cn.terminus.client.customer.contractselldefypaymentoverdueinfo.param.ContractSellDefyPaymentOverdueInfoQueryParam;
import cn.terminus.client.customer.contractselldefypaymentoverdueinfo.result.ContractSellDefyPaymentOverdueInfoResult;
import cn.terminus.client.customer.contractselldefypaymentoverdueinfo.service.ContractSellDefyPaymentOverdueInfoService;
import cn.terminus.client.customer.customcontacts.result.CustomContactsResult;
import cn.terminus.client.customer.custominfo.param.AddCustomInfoParam;
import cn.terminus.client.customer.custominfo.param.CustomInfoNewParam;
import cn.terminus.client.customer.custominfo.result.CustomInfoByNameResult;
import cn.terminus.client.customer.custominfo.service.CustomInfoService;
import cn.terminus.client.customer.custompurposeroom.param.CustomPurposeRoomNewParam;
import cn.terminus.client.customer.custompurposeroom.result.CustomPurposeRoomResult;
import cn.terminus.client.customer.custompurposeroom.result.RoomDetailResult;
import cn.terminus.common.customer.bean.analysis.AnalysisYearDto;
import cn.terminus.common.customer.bean.analysis.ContractTypeRoomDetail;
import cn.terminus.common.customer.bean.contractfile.dto.ContractFileNewDto;
import cn.terminus.common.customer.bean.contractinfo.dto.*;
import cn.terminus.common.customer.bean.contractrentdiscountclause.dto.ContractRentDiscountClauseNewDto;
import cn.terminus.common.customer.bean.contractrentincrementalclause.dto.ContractRentIncrementalClauseNewDto;
import cn.terminus.common.customer.bean.contractsellbystagesinfo.dto.ContractSellByStagesInfoNewDto;
import cn.terminus.common.customer.bean.contractsellclauseinfo.dto.ContractSellClauseInfoNewDto;
import cn.terminus.common.customer.bean.contractselldefylatedeliveryinfo.dto.ContractSellDefyLateDeliveryInfoNewDto;
import cn.terminus.common.customer.bean.contractselldefyloaninfo.dto.ContractSellDefyLoanInfoNewDto;
import cn.terminus.common.customer.bean.contractselldefyoverdueapplicationinfo.dto.ContractSellDefyOverdueApplicationInfoNewDto;
import cn.terminus.common.customer.bean.contractselldefypaymentoverdueinfo.dto.ContractSellDefyPaymentOverdueInfoNewDto;
import cn.terminus.common.customer.bean.customcontacts.dto.CustomContactsResultDto;
import cn.terminus.common.customer.bean.custominfo.dto.CustomInfoQueryNameResultDto;
import cn.terminus.common.customer.bean.custominfo.dto.GetCustomInfoByNameResultDto;
import cn.terminus.common.customer.bean.customlabel.dto.CustomLabelResultDto;
import cn.terminus.common.customer.bean.custompurposeroom.dto.*;
import cn.terminus.common.customer.constant.*;
import cn.terminus.result.common.annotation.TerminusParamVilidator;
import cn.terminus.result.common.context.TerminusCallContext;
import cn.terminus.result.common.exception.DataAccessException;
import cn.terminus.result.common.exception.ServiceException;
import cn.terminus.result.common.page.TerminusPageAble;
import cn.terminus.result.common.page.TerminusPageInfo;
import cn.terminus.result.common.result.TerminusResult;
import cn.terminus.result.common.util.BeanCopyUtils;
import cn.terminus.result.common.util.RedisUtils;
import cn.terminus.service.customer.analysis.AnalysisHandler;
import cn.terminus.service.customer.common.AbstractTerminusService;
import cn.terminus.service.customer.feign.carrier.CarrierFeignClient;
import cn.terminus.service.customer.feign.carrier.ProjectRoomDetailResult;
import cn.terminus.service.customer.job.RoomStatusHandler;
import cn.terminus.service.customer.kafka.KafkaContractParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 合同信息表(ContractInfo)表服务实现类
 *
 * @author makejava
 * @since 2021-07-21 11:01:07
 */
@Service
public class ContractInfoServiceImpl extends AbstractTerminusService implements ContractInfoService {
    /**
     * 日志
     */
    protected final Logger logger = LoggerFactory.getLogger(getClass());
    @Resource
    private ContractInfoManager contractInfoManager;

    @Autowired
    CustomInfoService customInfoService;

    @Autowired
    CustomPurposeRoomManager customPurposeRoomManager;

    @Autowired
    ContractRentClauseService contractRentClauseService;

    @Autowired
    ContractRentIncrementalClauseManager contractRentIncrementalClauseManager;

    @Autowired
    ContractRentDiscountClauseManager contractRentDiscountClauseManager;

    @Autowired
    ContractSellClauseInfoManager contractSellClauseInfoManager;

    @Autowired
    ContractSellByStagesInfoManager sellByStagesInfoManager;

    @Autowired
    ContractSellDefyPaymentOverdueInfoManager defyPaymentOverdueInfoManager;

    @Autowired
    ContractSellDefyLoanInfoManager sellDefyLoanInfoManager;

    @Autowired
    ContractSellDefyLateDeliveryInfoManager defyLateDeliveryInfoManager;

    @Autowired
    ContractSellDefyOverdueApplicationInfoManager defyOverdueApplicationInfoManager;

    @Autowired
    ContractFileManager contractFileManager;

    @Autowired
    CustomInfoManager customInfoManager;

    @Autowired
    CustomContactsManager customContactsManager;

    @Autowired
    ContractRentIncrementalClauseService contractRentIncrementalClauseService;

    @Autowired
    ContractRentDiscountClauseService contractRentDiscountClauseService;

    @Autowired
    ContractFileService contractFileService;

    @Autowired
    CarrierFeignClient carrierFeignClient;

    @Autowired
    ContractSellClauseInfoService sellClauseInfoService;

    @Autowired
    ContractSellByStagesInfoService sellByStagesInfoService;

    @Autowired
    ContractSellDefyPaymentOverdueInfoService sellDefyPaymentOverdueInfoService;

    @Autowired
    ContractSellDefyLoanInfoService loanInfoService;

    @Autowired
    ContractSellDefyLateDeliveryInfoService sellDefyLateDeliveryInfoService;

    @Autowired
    ContractSellDefyOverdueApplicationInfoService sellDefyOverdueApplicationInfoService;

    @Autowired
    ContractRentDiscountClauseManager rentDiscountClauseManager;

    @Autowired
    ContractSellDefyLoanInfoManager ContractSellDefyLoanInfoManager;

    @Autowired
    AnalysisHandler analysisHandler;

    @Autowired
    RoomStatusHandler roomStatusHandler;

    /**
     * 更新
     *
     * @param param
     * @param context
     * @return
     * @throws ServiceException
     */
    @Override
    @TerminusParamVilidator(argsIndexs = {0, 1})
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public TerminusResult<Boolean> update(ContractInfoEditParam param, TerminusCallContext context) throws ServiceException {
        ContractInfoEditDto editDto = new ContractInfoEditDto();
        BeanCopyUtils.copyProperties(param, context, editDto);
        try {
            contractInfoManager.update(editDto);
        } catch (DataAccessException e) {
            logger.error("更新失败,错误信息：{}", e.getMessage());
            throw new ServiceException(e);
        }
        return TerminusResult.success(true);
    }

    /**
     * 删除
     *
     * @param param
     * @param context
     * @return
     * @throws ServiceException
     */
    @Override
    @TerminusParamVilidator(argsIndexs = {0, 1})
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public TerminusResult<Boolean> delete(ContractInfoDeleteParam param, TerminusCallContext context) throws ServiceException {
        ContractInfoDeleteDto deleteDto = new ContractInfoDeleteDto();
        BeanCopyUtils.copyProperties(param, context, deleteDto);
        try {
            contractInfoManager.delete(deleteDto);
        } catch (DataAccessException e) {
            logger.error("删除失败,错误信息：{}", e.getMessage());
            throw new ServiceException(e);
        }
        return TerminusResult.success(true);
    }


    /**
     * 查询
     *
     * @param param
     * @param context
     * @return
     * @throws ServiceException
     */
    @Override
    @TerminusParamVilidator(argsIndexs = {0, 1})
    public TerminusResult<List<ContractInfoResult>> query(ContractInfoQueryParam param, TerminusCallContext context) throws ServiceException {
        ContractInfoQueryDto queryDto = new ContractInfoQueryDto();
        BeanCopyUtils.copyProperties(param, queryDto);
        try {
            List<ContractInfoResultDto> queryResultList = contractInfoManager.query(queryDto);
            return TerminusResult.success(BeanCopyUtils.copy(queryResultList, ContractInfoResult.class));
        } catch (DataAccessException e) {
            logger.error("查询失败,错误信息：{}", e.getMessage());
            throw new ServiceException(e);
        }

    }

    /**
     * 查询
     *
     * @param param
     * @param context
     * @return
     * @throws ServiceException
     */
    @Override
    @TerminusParamVilidator(argsIndexs = {0, 1})
    public TerminusResult<List<ContractInfoResult>> gets(ContractInfoGetsParam param, TerminusCallContext context) throws ServiceException {
        ContractInfoGetsDto getsDto = new ContractInfoGetsDto();
        BeanCopyUtils.copyProperties(param, getsDto);
        try {
            List<ContractInfoResultDto> getsResultList = contractInfoManager.gets(getsDto);
            return TerminusResult.success(BeanCopyUtils.copy(getsResultList, ContractInfoResult.class));
        } catch (DataAccessException e) {
            logger.error("查询失败,错误信息：{}", e.getMessage());
            throw new ServiceException(e);
        }
    }

    /**
     * 分页查询
     *
     * @param param
     * @param context
     * @return
     * @throws ServiceException
     */
    @Override
    @TerminusParamVilidator(argsIndexs = {0, 1})
    public TerminusResult<TerminusPageAble<ContractInfoResult>> page(ContractInfoQueryParam param, TerminusPageInfo page, TerminusCallContext context) throws ServiceException {
        ContractPageQueryDto queryDto = new ContractPageQueryDto();
        BeanCopyUtils.queryCopyProperties(param, context, queryDto);
        try {
            Long projectId = param.getProjectId();
            if (projectId != null && projectId > 0) {
                List<Long> contractIds = getContractIdsByProjectId(context, projectId);
                if (contractIds != null && contractIds.size() > 0) {
                    queryDto.setContractIds(contractIds);
                } else {
                    // 没有对于的数据 直接返回
                    return TerminusResult.success(new TerminusPageAble<>(new ArrayList<>(), page, 0));
                }

            }

            TerminusPageAble<ContractInfoResultDto> TerminusPageAble = contractInfoManager.page(queryDto, page);
            if (CollectionUtils.isEmpty(TerminusPageAble.getDatas())) {
                return TerminusResult.success(new TerminusPageAble<>(new ArrayList<>(), page, 0));
            }
            List<ContractInfoResult> results = BeanCopyUtils.copy(TerminusPageAble.getDatas(), ContractInfoResult.class);
            if (results != null && results.size() > 0) {
                Map<Long, String> customNameMap = null;
                Map<Long, List<CustomContactsResultDto>> customContactMap = null;
                List<Long> customerIdList = results.stream().map(ContractInfoResult::getCustomerId).distinct()
                        .collect(Collectors.toList());

                List<Long> contractIds = results.stream().map(ContractInfoResult::getId).distinct()
                        .collect(Collectors.toList());
                CustomRoomInfoGetDto roomInfoGetDto = new CustomRoomInfoGetDto();
                roomInfoGetDto.setContractIds(contractIds);
                roomInfoGetDto.setType(CustomPurposeRoomTypeEnum.CONTRACT.getCode());
                List<CustomPurposeRoomResultDto> roomResultDtos = customPurposeRoomManager.queryByContractIdsAndType(roomInfoGetDto);
                Map<Long, List<CustomPurposeRoomResultDto>> contractRoomMaps = null;
                Map<Long, ProjectRoomDetailResult> roomMap = null;
                if (roomResultDtos != null && roomResultDtos.size() > 0) {
                    contractRoomMaps = roomResultDtos.stream().collect(Collectors.groupingBy(CustomPurposeRoomResultDto::getContractId));

                    List<Long> roomIds = roomResultDtos.stream().map(CustomPurposeRoomResultDto::getCboRoomId).distinct().collect(Collectors.toList());
                    if (roomIds.size() > 0) {
                        TerminusResult<List<ProjectRoomDetailResult>> projectRooms = carrierFeignClient.getDetailByIds(roomIds);
                        List<ProjectRoomDetailResult> roomsData = projectRooms.getData();
                        if (roomsData != null && roomsData.size() > 0) {
                            roomMap = roomsData.stream().collect(Collectors.toMap(ProjectRoomDetailResult::getId, Function.identity()));
                        }
                    }
                }
                List<CustomContactsResultDto> contactsResults = customContactsManager.queryByCustomIds(customerIdList);
                if (contactsResults != null) {
                    customContactMap = contactsResults
                            .stream()
                            .collect(Collectors.groupingBy(CustomContactsResultDto::getCustomId));
                }

                List<CustomInfoQueryNameResultDto> customInfoResultDtos = customInfoManager.queryByIds(customerIdList);
                if (customInfoResultDtos != null && customInfoResultDtos.size() > 0) {
                    customNameMap = customInfoResultDtos
                            .stream()
                            .collect(Collectors.toMap(CustomInfoQueryNameResultDto::getId, CustomInfoQueryNameResultDto::getCboCustomName));
                }
                Map<Long, String> finalCustomNameMap = customNameMap;
                Map<Long, List<CustomContactsResultDto>> finalCustomContactMap = customContactMap;
                Map<Long, List<CustomPurposeRoomResultDto>> finalContractRoomMaps = contractRoomMaps;
                Map<Long, ProjectRoomDetailResult> finalRoomMap = roomMap;
                results.stream().forEach(r -> {
                    if (finalContractRoomMaps != null && finalContractRoomMaps.size() > 0) {
                        List<CustomPurposeRoomResultDto> roomResultDtoList = finalContractRoomMaps.get(r.getId());
                        if (!CollectionUtils.isEmpty(roomResultDtoList)) {
                            List<RoomDetailResult> ProjectRoomDetailResults = roomResultDtoList.stream().map(roo -> {
                                RoomDetailResult roomDetailResult = new RoomDetailResult();
                                Long cboRoomId = roo.getCboRoomId();
                                ProjectRoomDetailResult projectRoomDetailResult = finalRoomMap.get(cboRoomId);
                                BeanCopyUtils.copyProperties(projectRoomDetailResult, roomDetailResult);
                                return roomDetailResult;
                            }).collect(Collectors.toList());
                            r.setRoomDetailResults(ProjectRoomDetailResults);
                        }
                    }
                    if (finalCustomNameMap != null) {
                        String name = finalCustomNameMap.get(r.getCustomerId());
                        if (name != null) {
                            r.setCustomerName(name);
                        }
                    }

                    if (finalCustomContactMap != null) {
                        List<CustomContactsResultDto> customContactsResultDtos = finalCustomContactMap.get(r.getCustomerId());
                        if (customContactsResultDtos != null) {
                            List<CustomContactsResult> customContactsResults = customContactsResultDtos
                                    .stream()
                                    .map(c -> BeanCopyUtils.copyProperties(c, CustomContactsResult.class))
                                    .collect(Collectors.toList());
                            r.setCustomContactsResultList(customContactsResults);
                        }
                    }

                });
            }

            return TerminusResult.success(new TerminusPageAble<>(results,
                    page, TerminusPageAble.getTotalRows()));
        } catch (DataAccessException e) {
            logger.error("分页查询失败,错误信息：{}", e.getMessage());
            throw new ServiceException(e);
        }

    }

    private List<Long> getContractIdsByProjectId(TerminusCallContext context, Long projectId) throws DataAccessException {
        List<Long> contractIds = null;
        CustomPurposeRoomQueryDto roomQueryDto = new CustomPurposeRoomQueryDto();
        roomQueryDto.setType(CustomPurposeRoomTypeEnum.CONTRACT.getCode());
        //roomQueryDto.setBusinessId(context.getBusiness().getBusinessId());
        roomQueryDto.setCboProjectId(projectId);
        List<CustomPurposeRoomResultDto> roomResultDtos = customPurposeRoomManager.query(roomQueryDto);
        if (roomResultDtos != null && roomResultDtos.size() > 0) {
            contractIds = roomResultDtos.stream().map(CustomPurposeRoomResultDto::getContractId).distinct().collect(Collectors.toList());
        }
        return contractIds;
    }


    @Override
    @TerminusParamVilidator(argsIndexs = {0, 1})
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public TerminusResult<String> addRentContract(RentContractNewParam param, TerminusCallContext context) throws ServiceException {
        ContractInfoNewDto newDto = new ContractInfoNewDto();
        BeanCopyUtils.copyProperties(param, context, newDto);
        newDto.setId(genUUID());
        newDto.setStatus(ContractStatusEnum.OPEN.getCode());
        newDto.setType(ContractTypeEnum.rent.getCode());
        try {
            Long customerId = param.getCustomerId();
            if (customerId == null || customerId < 1) {
                AddCustomInfoParam customInfoParam = param.getCustomInfoParam();
                if (customInfoParam == null) {
                    return TerminusResult.fail("111", "客户信息不能为空");
                }
                //招商阶段
                CustomInfoNewParam customInfoNewForm = customInfoParam.getCustomInfoNewForm();
                customInfoNewForm.setCboCustomStage(DictCodeConstant.CUSTOMSTAGE3);
                TerminusResult<String> customerResult = customInfoService.addDetail(customInfoParam, context);
                if (!customerResult.isSuccess()) {
                    return customerResult;
                }
                customerId = Long.parseLong(customerResult.getData());
            }
            newDto.setCustomerId(customerId);
            contractInfoManager.add(newDto);
            List<CustomPurposeRoomNewParam> purposeRoomNewList = param.getPurposeRoomNewList();
            if (purposeRoomNewList != null && purposeRoomNewList.size() > 0) {
                // 新加房源信息
                addRooms(context, newDto.getId(), purposeRoomNewList);
            }
            //租金条款添加
            ContractRentClauseNewParam contractRentClauseNewParam = param.getContractRentClauses();
            if (contractRentClauseNewParam == null) {
                return TerminusResult.fail("111", "租金条款不能为空");
            }
            contractRentClauseNewParam.setContractId(newDto.getId());
            contractRentClauseService.add(contractRentClauseNewParam, context);

            List<ContractRentIncrementalClauseNewParam> incrementalClauseNewParams = param.getIncrementalClauseNewParams();
            if (incrementalClauseNewParams != null && incrementalClauseNewParams.size() > 0) {
                addRentIncrementalClauses(context, newDto.getId(), incrementalClauseNewParams);
            }

            List<ContractRentDiscountClauseNewParam> discountClauseNewParams = param.getDiscountClauseNewParams();
            if (discountClauseNewParams != null && discountClauseNewParams.size() > 0) {
                addRentDiscountClauses(context, newDto.getId(), discountClauseNewParams);
            }
            List<ContractFileNewParam> fileNewParamList = param.getFileNewParamList();
            if (fileNewParamList != null && fileNewParamList.size() > 0) {
                addFiles(newDto.getId(), fileNewParamList, context.getUser().getCallerName());
            }

            //新增租赁合同,渠道联系人销售量发送kafka
            GetCustomInfoByNameResultDto customerInfo = customInfoManager.getDetailById(customerId);
            String cboChannelUser = customerInfo.getCboChannelUser();
            String finalCboChannelUser = cboChannelUser == null ? "-1" : cboChannelUser;
            CompletableFuture.runAsync(() -> {
                sendAddRentContractMessage(purposeRoomNewList, context, finalCboChannelUser);
            });

            // 合同对应的房间状态变化消息推送
            LocalDate effectiveBeginTime = param.getEffectiveBeginTime();
            LocalDate effectiveEndTime = param.getEffectiveEndTime();
            LocalDate now = LocalDate.now();
            if ((now.isAfter(effectiveBeginTime) && now.isBefore(effectiveEndTime))
                    || now.isEqual(effectiveBeginTime) || now.isEqual(effectiveEndTime)) {
                // 在时间范围内 修改房间状态
                roomStatusHandler.sendBatchMsgWithEffective(purposeRoomNewList, ContractTypeEnum.rent.getCode());
            }
        } catch (DataAccessException e) {
            logger.error("新增失败,错误信息：{}", e.getMessage());
            throw new ServiceException(e);
        }

        return TerminusResult.success(String.valueOf(newDto.getId()));
    }

    private void sendAddRentContractMessage(List<CustomPurposeRoomNewParam> purposeRoomNewList, TerminusCallContext context, String cboChannelUser) {
        List<Long> roomIdList = null;
        if (!CollUtil.isEmpty(purposeRoomNewList)) {
            for (CustomPurposeRoomNewParam room : purposeRoomNewList) {
                this.sendContractKafka(KafkaContractParam.setContractMessage(context, room.getCboProjectId(), String.valueOf(ContractTypeEnum.rent.getCode()),
                        room.getCboRoomId(), 1, 1, StatusEnum.ADD.getCode(), Long.parseLong(cboChannelUser)));
            }

        }
    }


    @Override
    @TerminusParamVilidator(argsIndexs = {0, 1})
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public TerminusResult<String> addSellContract(SellContractNewParam param, TerminusCallContext context) throws ServiceException {
        ContractInfoNewDto newDto = new ContractInfoNewDto();
        BeanCopyUtils.copyProperties(param, context, newDto);
        newDto.setId(genUUID());
        newDto.setStatus(ContractStatusEnum.OPEN.getCode());
        newDto.setType(ContractTypeEnum.sell.getCode());

        try {
            Long customerId = param.getCustomerId();
            if (customerId == null || customerId < 1) {
                AddCustomInfoParam customInfoParam = param.getCustomInfoParam();
                if (customInfoParam == null) {
                    return TerminusResult.fail("111", "");
                }
                CustomInfoNewParam customInfoNewForm = customInfoParam.getCustomInfoNewForm();
                customInfoNewForm.setCboCustomStage(DictCodeConstant.CUSTOMSTAGE3);
                TerminusResult<String> customer = customInfoService.addDetail(customInfoParam, context);
                customerId = Long.parseLong(customer.getData());
            }
            newDto.setCustomerId(customerId);
            contractInfoManager.add(newDto);
            List<CustomPurposeRoomNewParam> purposeRoomNewList = param.getPurposeRoomNewList();
            if (purposeRoomNewList != null && purposeRoomNewList.size() > 0) {
                // 新加房源信息
                addRooms(context, newDto.getId(), purposeRoomNewList);
            }

            ContractSellClauseInfoNewParam sellClauseInfoNewParam = param.getSellClauseInfoNewParam();
            if (sellClauseInfoNewParam != null) {
                addSellClauseInfo(param, newDto.getId(), sellClauseInfoNewParam);
            }

            ContractSellDefyPaymentOverdueInfoNewParam defyPaymentOverdueInfoNewParam = param.getDefyPaymentOverdueInfoNewParam();
            if (defyPaymentOverdueInfoNewParam != null) {
                ContractSellDefyPaymentOverdueInfoNewDto contractSellDefyPaymentOverdueInfoNewDto = new ContractSellDefyPaymentOverdueInfoNewDto();
                BeanCopyUtils.copyProperties(defyPaymentOverdueInfoNewParam, contractSellDefyPaymentOverdueInfoNewDto);
                contractSellDefyPaymentOverdueInfoNewDto.setId(genUUID());
                contractSellDefyPaymentOverdueInfoNewDto.setContractId(newDto.getId());
                defyPaymentOverdueInfoManager.add(contractSellDefyPaymentOverdueInfoNewDto);
            }

            ContractSellDefyLoanInfoNewParam defyLoanInfoNewParam = param.getDefyLoanInfoNewParam();
            if (defyLoanInfoNewParam != null) {
                ContractSellDefyLoanInfoNewDto contractSellDefyLoanInfoNewDto = new ContractSellDefyLoanInfoNewDto();
                BeanCopyUtils.copyProperties(defyLoanInfoNewParam, contractSellDefyLoanInfoNewDto);
                contractSellDefyLoanInfoNewDto.setContractId(newDto.getId());
                contractSellDefyLoanInfoNewDto.setId(genUUID());
                ContractSellDefyLoanInfoManager.add(contractSellDefyLoanInfoNewDto);
            }

            ContractSellDefyLateDeliveryInfoNewParam defyLateDeliveryInfoNewParam = param.getDefyLateDeliveryInfoNewParam();
            if (defyLateDeliveryInfoNewParam != null) {
                ContractSellDefyLateDeliveryInfoNewDto contractSellDefyLateDeliveryInfoNewDto = new ContractSellDefyLateDeliveryInfoNewDto();
                BeanUtils.copyProperties(defyLateDeliveryInfoNewParam, contractSellDefyLateDeliveryInfoNewDto);
                contractSellDefyLateDeliveryInfoNewDto.setContractId(newDto.getId());
                contractSellDefyLateDeliveryInfoNewDto.setId(genUUID());
                defyLateDeliveryInfoManager.add(contractSellDefyLateDeliveryInfoNewDto);
            }

            ContractSellDefyOverdueApplicationInfoNewParam defyOverdueApplicationInfoNewParam = param.getDefyOverdueApplicationInfoNewParam();
            if (defyOverdueApplicationInfoNewParam != null) {
                ContractSellDefyOverdueApplicationInfoNewDto contractSellDefyOverdueApplicationInfoNewDto = new ContractSellDefyOverdueApplicationInfoNewDto();
                BeanCopyUtils.copyProperties(defyOverdueApplicationInfoNewParam, contractSellDefyOverdueApplicationInfoNewDto);
                contractSellDefyOverdueApplicationInfoNewDto.setContractId(newDto.getId());
                contractSellDefyOverdueApplicationInfoNewDto.setId(genUUID());
                defyOverdueApplicationInfoManager.add(contractSellDefyOverdueApplicationInfoNewDto);
            }

            List<ContractFileNewParam> fileNewParamList = param.getFileNewParamList();
            if (fileNewParamList != null && fileNewParamList.size() > 0) {
                addFiles(newDto.getId(), fileNewParamList, context.getUser().getCallerName());
            }

            //新增销售合同发送kafka
            GetCustomInfoByNameResultDto customerInfo = customInfoManager.getDetailById(customerId);
            String cboChannelUser = customerInfo.getCboChannelUser();
            String finalCboChannelUser = cboChannelUser == null ? "-1" : cboChannelUser;
            CompletableFuture.runAsync(() -> {
                sendAddSellContractMessage(purposeRoomNewList, context, finalCboChannelUser);
            });


            // 合同对应的房间状态变化消息推送
            LocalDate effectiveBeginTime = param.getEffectiveBeginTime();
            LocalDate now = LocalDate.now();
            if (now.isAfter(effectiveBeginTime) || now.isEqual(effectiveBeginTime)) {
                // 在时间范围内 修改房间状态
                roomStatusHandler.sendBatchMsgWithEffective(purposeRoomNewList, ContractTypeEnum.sell.getCode());
            }
        } catch (DataAccessException e) {
            logger.error("新增失败,错误信息：{}", e.getMessage());
            throw new ServiceException(e);
        }

        return TerminusResult.success(String.valueOf(newDto.getId()));
    }

    private void sendAddSellContractMessage(List<CustomPurposeRoomNewParam> purposeRoomNewList, TerminusCallContext context, String cboChannelUser) {
        if (!CollUtil.isEmpty(purposeRoomNewList)) {
            for (CustomPurposeRoomNewParam room : purposeRoomNewList) {
                this.sendContractKafka(KafkaContractParam.setContractMessage(context, room.getCboProjectId(), String.valueOf(ContractTypeEnum.sell.getCode()),
                        room.getCboRoomId(), 1, 1, StatusEnum.ADD.getCode(), Long.parseLong(cboChannelUser)));
            }
        }
    }


    @Override
    public TerminusResult<String> getCode(Integer type, TerminusCallContext terminusContext) {
        String code = "";
        LocalDate now = LocalDate.now();
        long number = RedisUtils.incr(ContractConstant.CONTRACTCODEINC);
        String numString = String.format("%06d", number);
        String timeCode = now.getYear() + "" + now.getMonthValue() + "" + now.getDayOfMonth();
        if (type == ContractTypeEnum.rent.getCode()) {
            code = "RCBO" + timeCode + numString;
        }
        if (type == ContractTypeEnum.sell.getCode()) {
            code = "SCBO" + timeCode + numString;
        }
        return TerminusResult.success(code);
    }

    @Override
    public TerminusResult<SellContractInfoDetailResult> querySellById(Long id, TerminusCallContext context) throws ServiceException {
        ContractInfoGetsDto contractInfoGetsDto = new ContractInfoGetsDto();
        contractInfoGetsDto.setIds(Arrays.asList(id.toString()));
        SellContractInfoDetailResult sellContractInfoDetailResult = new SellContractInfoDetailResult();

        try {
            List<ContractInfoResultDto> resultDtos = contractInfoManager.gets(contractInfoGetsDto);
            if (resultDtos == null || resultDtos.size() < 1) {
                return TerminusResult.fail("11", "id err");
            }
            BeanUtils.copyProperties(resultDtos.get(0), sellContractInfoDetailResult);
            GetCustomInfoByNameResultDto customInfoDto = customInfoManager.getDetailById(sellContractInfoDetailResult.getCustomerId());
            if (customInfoDto != null) {
                CustomInfoByNameResult customInfoResult = new CustomInfoByNameResult();
                BeanUtils.copyProperties(customInfoDto, customInfoResult);
                List<CustomLabelResultDto> cboCustomLabelList = customInfoDto.getCboCustomLabelList();
                if (cboCustomLabelList != null && cboCustomLabelList.size() > 0) {
                    List<String> customLabelResults = cboCustomLabelList
                            .stream()
                            .map(CustomLabelResultDto::getCboCustomLabel)
                            .collect(Collectors.toList());
                    BeanCopyUtils.copyProperties(cboCustomLabelList, customLabelResults);
                    customInfoResult.setCboCustomLabelList(customLabelResults);
                }
                List<CustomContactsResultDto> customContactsList = customInfoDto.getCustomContactsList();
                if (customContactsList != null && customContactsList.size() > 0) {
                    List<CustomContactsResult> customContactsResults = customContactsList.stream().map(c -> {
                        CustomContactsResult customContactsResult = new CustomContactsResult();
                        BeanCopyUtils.copyProperties(c, customContactsResult);
                        return customContactsResult;
                    }).collect(Collectors.toList());
                    customInfoResult.setCustomContactsList(customContactsResults);
                }
                sellContractInfoDetailResult.setCustomInfo(customInfoResult);
            }
            CustomPurposeRoomQueryDto customPurposeRoomQueryDto = new CustomPurposeRoomQueryDto();
            customPurposeRoomQueryDto.setContractId(sellContractInfoDetailResult.getId());
            customPurposeRoomQueryDto.setType(CustomPurposeRoomTypeEnum.CONTRACT.getCode());
            List<CustomPurposeRoomResultDto> roomResultDtos = customPurposeRoomManager.query(customPurposeRoomQueryDto);
            if (roomResultDtos != null && roomResultDtos.size() > 0) {
                List<Long> roomIds = roomResultDtos.stream().map(CustomPurposeRoomResultDto::getCboRoomId)
                        .collect(Collectors.toList());
                TerminusResult<List<ProjectRoomDetailResult>> roomDetailResult = carrierFeignClient.getDetailByIds(roomIds);
                if (!CollectionUtils.isEmpty(roomDetailResult.getData())) {
                    List<RoomDetailResult> roomDetailResultList = roomDetailResult.getData().stream().map(room -> {
                        RoomDetailResult roomDetail = new RoomDetailResult();
                        BeanCopyUtils.copyProperties(room, roomDetail);
                        roomDetail.setCboRoomId(room.getId());
                        return roomDetail;

                    }).collect(Collectors.toList());
                    sellContractInfoDetailResult.setRoomDetailResults(roomDetailResultList);
                }
            }
            // 条款信息
            ContractSellClauseInfoQueryParam contractSellClauseInfoQueryParam = new ContractSellClauseInfoQueryParam();
            contractSellClauseInfoQueryParam.setContractId(id);
            TerminusResult<List<ContractSellClauseInfoResult>> sellClausInfo = sellClauseInfoService.query(contractSellClauseInfoQueryParam, context);
            List<ContractSellClauseInfoResult> sellClausInfoData = sellClausInfo.getData();
            if (sellClausInfoData != null && sellClausInfoData.size() > 0) {
                ContractSellClauseInfoResult contractSellClauseInfoResult = sellClausInfoData.get(0);
                sellContractInfoDetailResult.setContractSellClauseInfoResult(contractSellClauseInfoResult);
                String paymentMethod = contractSellClauseInfoResult.getPaymentMethodCodeCode();
                if ("2".equals(paymentMethod)) {
                    // 分期付款，加分期逻辑
                    Long clauseId = contractSellClauseInfoResult.getId();
                    ContractSellByStagesInfoQueryParam sellByStagesInfoQueryParam = new ContractSellByStagesInfoQueryParam();
                    sellByStagesInfoQueryParam.setCboContractSellClauseInfoId(clauseId);
                    TerminusResult<List<ContractSellByStagesInfoResult>> sellByStages = sellByStagesInfoService.query(sellByStagesInfoQueryParam, context);
                    List<ContractSellByStagesInfoResult> sellByStagesData = sellByStages.getData();
                    if (sellByStagesData != null && sellByStagesData.size() > 0) {
                        sellContractInfoDetailResult.setSellByStagesInfoResults(sellByStagesData);
                    }
                }
                ContractSellDefyPaymentOverdueInfoQueryParam contractSellDefyPaymentOverdueInfoQueryParam = new ContractSellDefyPaymentOverdueInfoQueryParam();
                contractSellDefyPaymentOverdueInfoQueryParam.setContractId(id);
                // 付款逾期
                TerminusResult<List<ContractSellDefyPaymentOverdueInfoResult>> sellDefyPaymentOverdueInfoResults = sellDefyPaymentOverdueInfoService.query(contractSellDefyPaymentOverdueInfoQueryParam, context);
                List<ContractSellDefyPaymentOverdueInfoResult> sellDefyPaymentOverdueInfoResultsData = sellDefyPaymentOverdueInfoResults.getData();
                if (sellDefyPaymentOverdueInfoResultsData != null && sellDefyPaymentOverdueInfoResultsData.size() > 0) {
                    sellContractInfoDetailResult.setSellDefyPaymentOverdueInfoResult(sellDefyPaymentOverdueInfoResultsData.get(0));
                }
                //贷款逾期
                ContractSellDefyLoanInfoQueryParam contractSellDefyLoanInfoQueryParam = new ContractSellDefyLoanInfoQueryParam();
                contractSellDefyLoanInfoQueryParam.setContractId(id);

                TerminusResult<List<ContractSellDefyLoanInfoResult>> sellDefyLoanInfo = loanInfoService.query(contractSellDefyLoanInfoQueryParam, context);
                List<ContractSellDefyLoanInfoResult> sellDefyLoanInfoData = sellDefyLoanInfo.getData();
                if (sellDefyLoanInfoData != null && sellDefyLoanInfoData.size() > 0) {
                    sellContractInfoDetailResult.setLoanInfoResult(sellDefyLoanInfoData.get(0));
                }
                //交付逾期
                ContractSellDefyLateDeliveryInfoQueryParam contractSellDefyLateDeliveryInfoQueryParam = new ContractSellDefyLateDeliveryInfoQueryParam();
                contractSellDefyLateDeliveryInfoQueryParam.setContractId(id);
                TerminusResult<List<ContractSellDefyLateDeliveryInfoResult>> sellDefyLateDeliveryInfo = sellDefyLateDeliveryInfoService.query(contractSellDefyLateDeliveryInfoQueryParam, context);
                List<ContractSellDefyLateDeliveryInfoResult> sellDefyLateDeliveryInfoData = sellDefyLateDeliveryInfo.getData();
                if (sellDefyLateDeliveryInfoData != null && sellDefyLateDeliveryInfoData.size() > 0) {
                    sellContractInfoDetailResult.setSellDefyLateDeliveryInfoResult(sellDefyLateDeliveryInfoData.get(0));
                }
                //办证逾期
                ContractSellDefyOverdueApplicationInfoQueryParam contractSellDefyOverdueApplicationInfoQueryParam = new ContractSellDefyOverdueApplicationInfoQueryParam();
                contractSellDefyOverdueApplicationInfoQueryParam.setContractId(id);
                TerminusResult<List<ContractSellDefyOverdueApplicationInfoResult>> sellDefyOverdueApplicationInfo = sellDefyOverdueApplicationInfoService.query(contractSellDefyOverdueApplicationInfoQueryParam, context);
                List<ContractSellDefyOverdueApplicationInfoResult> sellDefyOverdueApplicationInfoData = sellDefyOverdueApplicationInfo.getData();
                if (sellDefyOverdueApplicationInfoData != null && sellDefyOverdueApplicationInfoData.size() > 0) {
                    sellContractInfoDetailResult.setDefyOverdueApplicationInfoResult(sellDefyOverdueApplicationInfoData.get(0));
                }
                // 文件信息
                ContractFileQueryParam contractFileQueryParam = new ContractFileQueryParam();
                contractFileQueryParam.setContractId(id);
                TerminusResult<List<ContractFileResult>> files = contractFileService.query(contractFileQueryParam, context);
                List<ContractFileResult> filesData = files.getData();
                if (filesData != null && filesData.size() > 0) {
                    sellContractInfoDetailResult.setFileList(filesData);
                }
            }


        } catch (DataAccessException e) {
            logger.error("查询合同详情,错误信息：{}", e.getMessage());
            throw new ServiceException(e);
        }
        return TerminusResult.success(sellContractInfoDetailResult);
    }

    @Override
    public TerminusResult<RentContractInfoDetailResult> queryRentById(Long id, TerminusCallContext terminusContext) throws ServiceException {
        ContractInfoGetsDto contractInfoGetsDto = new ContractInfoGetsDto();
        contractInfoGetsDto.setIds(Arrays.asList(id.toString()));
        RentContractInfoDetailResult rentContractInfoDetailResult = new RentContractInfoDetailResult();

        try {
            List<ContractInfoResultDto> resultDtos = contractInfoManager.gets(contractInfoGetsDto);
            if (resultDtos == null || resultDtos.size() < 1) {
                return TerminusResult.fail("11", "id err");
            }
            BeanUtils.copyProperties(resultDtos.get(0), rentContractInfoDetailResult);
            GetCustomInfoByNameResultDto customInfoDto = customInfoManager.getDetailById(rentContractInfoDetailResult.getCustomerId());
            if (customInfoDto != null) {
                CustomInfoByNameResult customInfoResult = new CustomInfoByNameResult();
                BeanUtils.copyProperties(customInfoDto, customInfoResult);
                List<CustomLabelResultDto> cboCustomLabelList = customInfoDto.getCboCustomLabelList();
                if (cboCustomLabelList != null && cboCustomLabelList.size() > 0) {
                    List<String> customLabelResults = cboCustomLabelList
                            .stream()
                            .map(CustomLabelResultDto::getCboCustomLabel)
                            .collect(Collectors.toList());
                    BeanCopyUtils.copyProperties(cboCustomLabelList, customLabelResults);
                    customInfoResult.setCboCustomLabelList(customLabelResults);
                }
                List<CustomContactsResultDto> customContactsList = customInfoDto.getCustomContactsList();
                if (customContactsList != null && customContactsList.size() > 0) {
                    List<CustomContactsResult> customContactsResults = customContactsList.stream().map(c -> {
                        CustomContactsResult customContactsResult = new CustomContactsResult();
                        BeanCopyUtils.copyProperties(c, customContactsResult);
                        return customContactsResult;
                    }).collect(Collectors.toList());
                    customInfoResult.setCustomContactsList(customContactsResults);
                }
                rentContractInfoDetailResult.setCustomInfo(customInfoResult);
            }
            CustomPurposeRoomQueryDto customPurposeRoomQueryDto = new CustomPurposeRoomQueryDto();
            customPurposeRoomQueryDto.setContractId(rentContractInfoDetailResult.getId());
            customPurposeRoomQueryDto.setType(CustomPurposeRoomTypeEnum.CONTRACT.getCode());
            List<CustomPurposeRoomResultDto> roomResultDtos = customPurposeRoomManager.query(customPurposeRoomQueryDto);
            if (roomResultDtos != null && roomResultDtos.size() > 0) {
                List<Long> roomIds = roomResultDtos.stream().map(CustomPurposeRoomResultDto::getCboRoomId)
                        .collect(Collectors.toList());
                TerminusResult<List<ProjectRoomDetailResult>> roomDetailResult = carrierFeignClient.getDetailByIds(roomIds);
                if (!CollectionUtils.isEmpty(roomDetailResult.getData())) {
                    List<RoomDetailResult> roomDetailResultList = roomDetailResult.getData().stream().map(room -> {
                        RoomDetailResult roomDetail = new RoomDetailResult();
                        BeanCopyUtils.copyProperties(room, roomDetail);
                        roomDetail.setCboRoomId(room.getId());
                        return roomDetail;

                    }).collect(Collectors.toList());
                    rentContractInfoDetailResult.setRoomDetailResults(roomDetailResultList);
                }
            }
            ContractRentClauseQueryParam contractRentClauseQueryParam = new ContractRentClauseQueryParam();
            contractRentClauseQueryParam.setContractId(rentContractInfoDetailResult.getId());
            TerminusResult<List<ContractRentClauseResult>> clauses = contractRentClauseService.query(contractRentClauseQueryParam, terminusContext);
            List<ContractRentClauseResult> clausesData = clauses.getData();
            if (clausesData != null && clausesData.size() > 0) {
                rentContractInfoDetailResult.setContractRentClauseResult(clausesData.get(0));
            }
            ContractRentIncrementalClauseQueryParam incrementalClauseQueryParam = new ContractRentIncrementalClauseQueryParam();
            incrementalClauseQueryParam.setContractId(rentContractInfoDetailResult.getId());
            TerminusResult<List<ContractRentIncrementalClauseResult>> incrementalClauseResult = contractRentIncrementalClauseService.query(incrementalClauseQueryParam, terminusContext);
            List<ContractRentIncrementalClauseResult> data = incrementalClauseResult.getData();
            if (data != null && data.size() > 0) {
                rentContractInfoDetailResult.setIncrementalClauseResults(data);
            }
            ContractRentDiscountClauseQueryParam discountClauseQueryParam = new ContractRentDiscountClauseQueryParam();
            discountClauseQueryParam.setContractId(rentContractInfoDetailResult.getId());
            TerminusResult<List<ContractRentDiscountClauseResult>> discountClauses = contractRentDiscountClauseService.query(discountClauseQueryParam, terminusContext);
            List<ContractRentDiscountClauseResult> discountClausesData = discountClauses.getData();
            if (discountClausesData != null && discountClausesData.size() > 0) {
                rentContractInfoDetailResult.setDiscountClausesData(discountClausesData);
            }
            ContractFileQueryParam contractFileQueryParam = new ContractFileQueryParam();
            contractFileQueryParam.setContractId(rentContractInfoDetailResult.getId());
            TerminusResult<List<ContractFileResult>> files = contractFileService.query(contractFileQueryParam, terminusContext);
            List<ContractFileResult> filesData = files.getData();
            if (filesData != null && filesData.size() > 0) {
                rentContractInfoDetailResult.setFileList(filesData);
            }

        } catch (DataAccessException e) {
            logger.error("查询合同详情,错误信息：{}", e.getMessage());
            throw new ServiceException(e);
        }
        return TerminusResult.success(rentContractInfoDetailResult);
    }

    @Override
    @TerminusParamVilidator(argsIndexs = {0, 1})
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public TerminusResult<Boolean> editRentContract(RentContractNewParam param, TerminusCallContext context) throws ServiceException {
        ContractInfoEditDto editDto = new ContractInfoEditDto();
        BeanCopyUtils.copyProperties(param, context, editDto);
        try {
            //查询修改之前的房源
            List<RoomDetailResult> roomDetailResults = getRoomDetailResults(param.getId(), context);

            Long customerId = param.getCustomerId();
            if (customerId == null || customerId < 1) {
                AddCustomInfoParam customInfoParam = param.getCustomInfoParam();
                if (customInfoParam == null) {
                    return TerminusResult.fail("111", "");
                }
                TerminusResult<String> customer = customInfoService.addDetail(customInfoParam, context);
                customerId = Long.parseLong(customer.getData());
            }
            editDto.setCustomerId(customerId);
            contractInfoManager.update(editDto);
            CustomPurposeRoomDeleteDto roomDeleteDto = new CustomPurposeRoomDeleteDto();
            roomDeleteDto.setContractId(editDto.getId());
            roomDeleteDto.setType(CustomPurposeRoomTypeEnum.CONTRACT.getCode());
            customPurposeRoomManager.delete(roomDeleteDto);
            List<CustomPurposeRoomNewParam> purposeRoomNewList = param.getPurposeRoomNewList();
            if (purposeRoomNewList != null && purposeRoomNewList.size() > 0) {
                // 新加房源信息
                addRooms(context, editDto.getId(), purposeRoomNewList);
            }
            //租金条款删除
            contractRentClauseService.deleteWithContractId(editDto.getId());
            //租金条款添加
            ContractRentClauseNewParam contractRentClauseNewParam = param.getContractRentClauses();
            if (contractRentClauseNewParam == null) {
                return TerminusResult.fail("111", "租金条款不能为空");
            }
            contractRentClauseNewParam.setContractId(editDto.getId());
            contractRentClauseService.add(contractRentClauseNewParam, context);


            List<ContractRentIncrementalClauseNewParam> incrementalClauseNewParams = param.getIncrementalClauseNewParams();
            contractRentIncrementalClauseManager.deleteWithContractId(editDto.getId());
            if (incrementalClauseNewParams != null && incrementalClauseNewParams.size() > 0) {
                addRentIncrementalClauses(context, editDto.getId(), incrementalClauseNewParams);
            }
            rentDiscountClauseManager.deleteWithContractId(editDto.getId());
            List<ContractRentDiscountClauseNewParam> discountClauseNewParams = param.getDiscountClauseNewParams();
            if (discountClauseNewParams != null && discountClauseNewParams.size() > 0) {
                addRentDiscountClauses(context, editDto.getId(), discountClauseNewParams);
            }
            contractFileManager.deleteWithContractId(editDto.getId());
            List<ContractFileNewParam> fileNewParamList = param.getFileNewParamList();
            if (fileNewParamList != null && fileNewParamList.size() > 0) {
                addFiles(editDto.getId(), fileNewParamList, context.getUser().getCallerName());
            }
            //发送修改租赁合同kafka
            GetCustomInfoByNameResultDto customerInfo = customInfoManager.getDetailById(customerId);
            String cboChannelUser = customerInfo.getCboChannelUser();
            String finalCboChannelUser = cboChannelUser == null ? "-1" : cboChannelUser;
            List<RoomDetailResult> finalRoomDetailResults = roomDetailResults;
            CompletableFuture.runAsync(() -> {
                sendUpdateRentContractMessage(finalRoomDetailResults, purposeRoomNewList, context, finalCboChannelUser);
                roomStatusHandler.sendMsgWithEditRentContract(finalRoomDetailResults, param);

            });
        } catch (DataAccessException e) {
            logger.error("新增失败,错误信息：{}", e.getMessage());
            throw new ServiceException(e);
        }
        return TerminusResult.success(Boolean.TRUE);
    }

    private List<RoomDetailResult> getRoomDetailResults(Long id, TerminusCallContext context) throws ServiceException {
        TerminusResult<RentContractInfoDetailResult> result = this.queryRentById(id, context);
        List<RoomDetailResult> roomDetailResults = new ArrayList<>();
        RentContractInfoDetailResult data = result.getData();
        if (BeanUtil.isNotEmpty(data)) {
            roomDetailResults = data.getRoomDetailResults();
        }
        return roomDetailResults;
    }

    private void sendUpdateRentContractMessage(List<RoomDetailResult> roomDetailResults, List<CustomPurposeRoomNewParam> purposeRoomNewList, TerminusCallContext context, String cboChannelUser) {
        //删除修改之前的数据
        if (BeanUtil.isNotEmpty(roomDetailResults)) {
            for (RoomDetailResult roomDetailResult : roomDetailResults) {
                this.sendContractKafka(KafkaContractParam.setContractMessage(context, roomDetailResult.getCboProjectId(), String.valueOf(ContractTypeEnum.rent.getCode()),
                        roomDetailResult.getCboRoomId(), -1, -1, StatusEnum.DELETE.getCode(), Long.parseLong(cboChannelUser)));
            }
        }
        //新增要修改的数据
        if (CollUtil.isNotEmpty(purposeRoomNewList)) {
            this.sendAddRentContractMessage(purposeRoomNewList, context, cboChannelUser);
        }
    }


    @Override
    @TerminusParamVilidator(argsIndexs = {0, 1})
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public TerminusResult<Boolean> editSellContract(SellContractNewParam param, TerminusCallContext context) throws ServiceException {
        ContractInfoEditDto editDto = new ContractInfoEditDto();
        BeanCopyUtils.copyProperties(param, context, editDto);
        try {
            List<RoomDetailResult> roomDetailResults = getRoomDetailResults(param.getId(), context);

            Long customerId = param.getCustomerId();
            if (customerId == null || customerId < 1) {
                AddCustomInfoParam customInfoParam = param.getCustomInfoParam();
                if (customInfoParam == null) {
                    return TerminusResult.fail("111", "");
                }
                TerminusResult<String> customer = customInfoService.addDetail(customInfoParam, context);
                customerId = Long.parseLong(customer.getData());
            }
            editDto.setCustomerId(customerId);
            contractInfoManager.update(editDto);
            // 删除房源
            CustomPurposeRoomDeleteDto roomDeleteDto = new CustomPurposeRoomDeleteDto();
            roomDeleteDto.setContractId(editDto.getId());
            roomDeleteDto.setType(CustomPurposeRoomTypeEnum.CONTRACT.getCode());
            customPurposeRoomManager.delete(roomDeleteDto);
            List<CustomPurposeRoomNewParam> purposeRoomNewList = param.getPurposeRoomNewList();
            if (purposeRoomNewList != null && purposeRoomNewList.size() > 0) {
                // 新加房源信息
                addRooms(context, editDto.getId(), purposeRoomNewList);
            }

            contractSellClauseInfoManager.deleteWithContractId(editDto.getId());
            ContractSellClauseInfoNewParam sellClauseInfoNewParam = param.getSellClauseInfoNewParam();
            if (sellClauseInfoNewParam != null) {
                addSellClauseInfo(param, editDto.getId(), sellClauseInfoNewParam);
            }
            defyPaymentOverdueInfoManager.deleteWithContractId(editDto.getId());
            ContractSellDefyPaymentOverdueInfoNewParam defyPaymentOverdueInfoNewParam = param.getDefyPaymentOverdueInfoNewParam();
            if (defyPaymentOverdueInfoNewParam != null) {
                ContractSellDefyPaymentOverdueInfoNewDto contractSellDefyPaymentOverdueInfoNewDto = new ContractSellDefyPaymentOverdueInfoNewDto();
                BeanCopyUtils.copyProperties(defyPaymentOverdueInfoNewParam, contractSellDefyPaymentOverdueInfoNewDto);
                contractSellDefyPaymentOverdueInfoNewDto.setId(genUUID());
                contractSellDefyPaymentOverdueInfoNewDto.setContractId(editDto.getId());
                defyPaymentOverdueInfoManager.add(contractSellDefyPaymentOverdueInfoNewDto);
            }

            ContractSellDefyLoanInfoManager.deleteWithContractId(editDto.getId());
            ContractSellDefyLoanInfoNewParam defyLoanInfoNewParam = param.getDefyLoanInfoNewParam();
            if (defyLoanInfoNewParam != null) {
                ContractSellDefyLoanInfoNewDto contractSellDefyLoanInfoNewDto = new ContractSellDefyLoanInfoNewDto();
                BeanCopyUtils.copyProperties(defyLoanInfoNewParam, contractSellDefyLoanInfoNewDto);
                contractSellDefyLoanInfoNewDto.setContractId(editDto.getId());
                contractSellDefyLoanInfoNewDto.setId(genUUID());
                ContractSellDefyLoanInfoManager.add(contractSellDefyLoanInfoNewDto);
            }

            defyLateDeliveryInfoManager.deleteWithContractId(editDto.getId());
            ContractSellDefyLateDeliveryInfoNewParam defyLateDeliveryInfoNewParam = param.getDefyLateDeliveryInfoNewParam();
            if (defyLateDeliveryInfoNewParam != null) {
                ContractSellDefyLateDeliveryInfoNewDto contractSellDefyLateDeliveryInfoNewDto = new ContractSellDefyLateDeliveryInfoNewDto();
                BeanUtils.copyProperties(defyLateDeliveryInfoNewParam, contractSellDefyLateDeliveryInfoNewDto);
                contractSellDefyLateDeliveryInfoNewDto.setContractId(editDto.getId());
                contractSellDefyLateDeliveryInfoNewDto.setId(genUUID());
                defyLateDeliveryInfoManager.add(contractSellDefyLateDeliveryInfoNewDto);
            }

            defyOverdueApplicationInfoManager.deleteWithContractId(editDto.getId());
            ContractSellDefyOverdueApplicationInfoNewParam defyOverdueApplicationInfoNewParam = param.getDefyOverdueApplicationInfoNewParam();
            if (defyOverdueApplicationInfoNewParam != null) {
                ContractSellDefyOverdueApplicationInfoNewDto contractSellDefyOverdueApplicationInfoNewDto = new ContractSellDefyOverdueApplicationInfoNewDto();
                BeanCopyUtils.copyProperties(defyOverdueApplicationInfoNewParam, contractSellDefyOverdueApplicationInfoNewDto);
                contractSellDefyOverdueApplicationInfoNewDto.setContractId(editDto.getId());
                contractSellDefyOverdueApplicationInfoNewDto.setId(genUUID());
                defyOverdueApplicationInfoManager.add(contractSellDefyOverdueApplicationInfoNewDto);
            }

            contractFileManager.deleteWithContractId(editDto.getId());

            List<ContractFileNewParam> fileNewParamList = param.getFileNewParamList();
            if (fileNewParamList != null && fileNewParamList.size() > 0) {
                addFiles(editDto.getId(), fileNewParamList, context.getUser().getCallerName());
            }

            //发送修改销售合同kafka
            GetCustomInfoByNameResultDto customerInfo = customInfoManager.getDetailById(customerId);
            String cboChannelUser = customerInfo.getCboChannelUser();
            String finalCboChannelUser = cboChannelUser == null ? "-1" : cboChannelUser;
            List<RoomDetailResult> finalRoomDetailResults = roomDetailResults;
            CompletableFuture.runAsync(() -> {
                sendUpdateSellContractMessage(finalRoomDetailResults, purposeRoomNewList, context, finalCboChannelUser);
                roomStatusHandler.sendMsgWithEditSellContract(finalRoomDetailResults, param);
            });

        } catch (DataAccessException e) {
            logger.error("新增失败,错误信息：{}", e.getMessage());
            throw new ServiceException(e);
        }
        return TerminusResult.success(true);
    }

    private void sendUpdateSellContractMessage(List<RoomDetailResult> roomDetailResults, List<CustomPurposeRoomNewParam> purposeRoomNewList, TerminusCallContext context, String cboChannelUser) {
        //删除修改之前的数据
        if (BeanUtil.isNotEmpty(roomDetailResults)) {
            for (RoomDetailResult roomDetailResult : roomDetailResults) {
                this.sendContractKafka(KafkaContractParam.setContractMessage(context, roomDetailResult.getCboProjectId(), String.valueOf(ContractTypeEnum.sell.getCode()),
                        roomDetailResult.getCboRoomId(), -1, -1, StatusEnum.DELETE.getCode(), Long.parseLong(cboChannelUser)));
            }
        }
        //新增要修改的数据
        if (CollUtil.isNotEmpty(purposeRoomNewList)) {
            this.sendAddSellContractMessage(purposeRoomNewList, context, cboChannelUser);
        }
    }

    @Override
    @TerminusParamVilidator(argsIndexs = {0, 1})
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public TerminusResult<Boolean> deleteByIds(ContractInfoDeleteParam param, TerminusCallContext terminusContext) throws ServiceException {
        try {
            List<Long> ids = param.getIds();
            List<ContractTypeRoomDetail> details = contractInfoManager.queryByIds(ids);
            //删除合同,渠道联系人销售量发送kafka
            List<ContractTypeRoomDetail> finalDetails = details;
            CompletableFuture.runAsync(() -> {
                try {
                    sendDeleteContractKafkaMessage(finalDetails, terminusContext);
                } catch (ServiceException e) {
                    e.printStackTrace();
                }
            });

            contractInfoManager.deleteByIds(ids);
            // 删除房源
            customPurposeRoomManager.deleteByContractIds(ids);

        } catch (DataAccessException e) {
            logger.error("删除失败,错误信息：{}", e.getMessage());
            throw new ServiceException(e);
        }
        return TerminusResult.success(true);

    }

    private void sendDeleteContractKafkaMessage(List<ContractTypeRoomDetail> details, TerminusCallContext context) throws ServiceException {
        Map<String, List<ContractTypeRoomDetail>> map = new HashMap<>();
        if (!CollUtil.isEmpty(details)) {
            for (ContractTypeRoomDetail result : details) {
                String key = result.getContractType() + "-" + result.getCboProjectId() + "-" + result.getCboRoomId();
                List<ContractTypeRoomDetail> keyList = map.get(key);
                if (CollUtil.isEmpty(keyList)) {
                    List<ContractTypeRoomDetail> newList = new ArrayList<>();
                    newList.add(result);
                    map.put(key, newList);
                } else {
                    keyList.add(result);
                }
                // 删除合同，使得房间状态失效
                roomStatusHandler.sendMsgWithInvalid(result.getContractType(), result.getCboRoomId());
            }
            for (List<ContractTypeRoomDetail> value : map.values()) {
                for (ContractTypeRoomDetail contractTypeRoomResult : value) {

                    this.sendContractKafka(KafkaContractParam.setContractMessage(context, contractTypeRoomResult.getCboProjectId(), String.valueOf(contractTypeRoomResult.getContractType()),
                            contractTypeRoomResult.getCboRoomId(), -1, -1, StatusEnum.DELETE.getCode(), contractTypeRoomResult.getCboChannelUser()));
                }
            }
        }

    }

    private void addFiles(Long contractId, List<ContractFileNewParam> fileNewParamList, String createUser) throws
            DataAccessException {
        List<ContractFileNewDto> fileNewDtoList = fileNewParamList.stream().map(f -> {
            ContractFileNewDto contractFileNewDto = new ContractFileNewDto();
            BeanCopyUtils.copyProperties(f, contractFileNewDto);
            contractFileNewDto.setContractId(contractId);
            contractFileNewDto.setId(genUUID());
            //contractFileNewDto.setCreateUser(createUser);
            contractFileNewDto.setCreateTime(new Date());
            contractFileNewDto.setCboFileOrder(1);
            return contractFileNewDto;
        }).collect(Collectors.toList());
        contractFileManager.insertBatch(fileNewDtoList);
    }

    private void addSellClauseInfo(SellContractNewParam param, Long contractId, ContractSellClauseInfoNewParam
            sellClauseInfoNewParam) throws DataAccessException {
        ContractSellClauseInfoNewDto contractSellClauseInfoNewDto = new ContractSellClauseInfoNewDto();
        BeanCopyUtils.copyProperties(sellClauseInfoNewParam, contractSellClauseInfoNewDto);
        contractSellClauseInfoNewDto.setContractId(contractId);
        contractSellClauseInfoNewDto.setId(genUUID());
        contractSellClauseInfoManager.add(contractSellClauseInfoNewDto);
        List<ContractSellByStagesInfoNewParam> sellByStagesInfoNewParamList = param.getSellByStagesInfoNewParamList();

        if (sellByStagesInfoNewParamList != null && sellByStagesInfoNewParamList.size() > 0) {
            List<ContractSellByStagesInfoNewDto> byStagesInfoNewDtos = sellByStagesInfoNewParamList.stream().map(s ->
            {
                ContractSellByStagesInfoNewDto contractSellByStagesInfoNewDto = new ContractSellByStagesInfoNewDto();
                BeanCopyUtils.copyProperties(s, contractSellByStagesInfoNewDto);
                contractSellByStagesInfoNewDto.setCboContractSellClauseInfoId(contractSellClauseInfoNewDto.getId());
                contractSellByStagesInfoNewDto.setId(genUUID());
                return contractSellByStagesInfoNewDto;
            }).collect(Collectors.toList());

            sellByStagesInfoManager.insertBatch(byStagesInfoNewDtos);
        }
    }


    private void addRentDiscountClauses(TerminusCallContext context, Long
            contractId, List<ContractRentDiscountClauseNewParam> discountClauseNewParams) throws DataAccessException {
        List<ContractRentDiscountClauseNewDto> dtos = discountClauseNewParams.stream().map(d -> {
            ContractRentDiscountClauseNewDto dto = new ContractRentDiscountClauseNewDto();
            BeanCopyUtils.copyProperties(d, context, dto);
            dto.setContractId(contractId);
            dto.setId(genUUID());
            return dto;
        }).collect(Collectors.toList());
        contractRentDiscountClauseManager.insertBatch(dtos);
    }

    private void addRentIncrementalClauses(TerminusCallContext context, Long
            contractId, List<ContractRentIncrementalClauseNewParam> incrementalClauseNewParams) throws
            DataAccessException {
        List<ContractRentIncrementalClauseNewDto> incrementalClauseNewDtos = incrementalClauseNewParams.stream().map(i -> {
            ContractRentIncrementalClauseNewDto contractRentIncrementalClauseNewDto = new ContractRentIncrementalClauseNewDto();
            BeanCopyUtils.copyProperties(i, context, contractRentIncrementalClauseNewDto);
            contractRentIncrementalClauseNewDto.setId(genUUID());
            contractRentIncrementalClauseNewDto.setContractId(contractId);
            return contractRentIncrementalClauseNewDto;
        }).collect(Collectors.toList());
        contractRentIncrementalClauseManager.insertBatch(incrementalClauseNewDtos);
    }

    private void addRooms(TerminusCallContext context, Long
            contractId, List<CustomPurposeRoomNewParam> purposeRoomNewList) throws DataAccessException {

        List<CustomPurposeRoomNewDto> roomNewDtos = purposeRoomNewList.stream().map(room -> {
            CustomPurposeRoomNewDto customPurposeRoomNewDto = new CustomPurposeRoomNewDto();
            BeanCopyUtils.copyProperties(room, context, customPurposeRoomNewDto);
            customPurposeRoomNewDto.setId(genUUID());
            customPurposeRoomNewDto.setContractId(contractId);
            customPurposeRoomNewDto.setType(CustomPurposeRoomTypeEnum.CONTRACT.getCode());
            return customPurposeRoomNewDto;

        }).collect(Collectors.toList());
        customPurposeRoomManager.addMulti(roomNewDtos);
    }


    @Override
    public TerminusResult<List<CustomPurposeRoomResult>> geturposeRoomInfoByContractIds
            (List<Long> contractIdList) throws ServiceException {

        try {
            List<CustomPurposeRoomResultDto> list = contractInfoManager.geturposeRoomInfoByContractIds(contractIdList);
            return TerminusResult.success(BeanCopyUtils.copy(list, CustomPurposeRoomResult.class));
        } catch (DataAccessException e) {
            logger.error("查询失败,错误信息：{}", e.getMessage());
            throw new ServiceException(e);
        }
    }

    @Override
    public TerminusResult<Boolean> queryRoomsWithContract(List<Long> ids, TerminusCallContext terminusContext) throws
            ServiceException {
        if (CollectionUtils.isEmpty(ids)) {
            return TerminusResult.fail("11", "ids不能为空");
        }
        try {
            Integer number = customPurposeRoomManager.countContractRooms(ids);
            if (number == null || number <= 0) {
                return TerminusResult.success(false);
            } else {
                return TerminusResult.success(true);
            }
        } catch (DataAccessException e) {
            logger.error("查询失败,错误信息：{}", e.getMessage());
            throw new ServiceException(e);
        }
    }

    @Override
    public TerminusResult<Integer> analysisTotalContract(AnalysisYearParam param, TerminusCallContext context) throws
            ServiceException {
        AnalysisYearDto dto = new AnalysisYearDto();
        BeanCopyUtils.queryCopyProperties(param, context, dto);
        try {
            Integer number = contractInfoManager.analysisTotalContract(dto);
            return TerminusResult.success(number);
        } catch (DataAccessException e) {
            logger.error("查询失败,错误信息：{}", e.getMessage());
            throw new ServiceException(e);
        }
    }

    @Override
    public TerminusResult<Boolean> getContractRoomsInfo(ContractRoomsInfoQueryParam param, TerminusCallContext terminusContext) throws ServiceException {
        Long roomId = param.getCboRoomId();
        Long projectId = param.getCboProjectId();
        if (roomId == null || projectId == null) {
            return TerminusResult.success(true);
        }
        CustomPurposeRoomQueryDto queryDto = BeanCopyUtils.copyProperties(param, CustomPurposeRoomQueryDto.class);
        queryDto.setType(CustomPurposeRoomTypeEnum.CONTRACT.getCode());
        try {
            List<CustomPurposeRoomResultDto> roomResult = customPurposeRoomManager.query(queryDto);
            if (!CollectionUtils.isEmpty(roomResult)) {
                List<String> contractIds = roomResult
                        .stream()
                        .map(c -> String.valueOf(c.getContractId()))
                        .collect(Collectors.toList());
                ContractInfoGetsDto getsDto = new ContractInfoGetsDto();
                getsDto.setIds(contractIds);
                List<ContractInfoResultDto> contractInfoResultDtos = contractInfoManager.gets(getsDto);
                if (!CollectionUtils.isEmpty(contractInfoResultDtos)) {
                    Boolean flag = roomUserCheck(param, contractInfoResultDtos);
                    return TerminusResult.success(!flag);
                }
            }
            return TerminusResult.success(true);
        } catch (DataAccessException e) {
            logger.error("查询失败,错误信息：{}", e.getMessage());
            throw new ServiceException(e);
        }

    }

    // 查看房间是否被占用了
    // true -> 房间被占用了   false-> 可用
    private Boolean roomUserCheck(ContractRoomsInfoQueryParam param, List<ContractInfoResultDto> contractInfoResultDtos) {
        Integer type = param.getType();
        //租赁时间判断
        // 房间被销售了  不管时间，都不能选择
        // 房间被租赁了  加时间判断
        //rent(1, "租赁"),
        //sell(2, "销售");
        if (ContractTypeEnum.rent.getCode().equals(type)) {
            for (ContractInfoResultDto c : contractInfoResultDtos) {
                Integer contractType = c.getType();
                LocalDate effectiveBeginTime = c.getEffectiveBeginTime();
                LocalDate effectiveEndTime = c.getEffectiveEndTime();
                // 销售合同存在
                if (ContractTypeEnum.sell.getCode().equals(contractType)) {
                    //
                    if (effectiveBeginTime.isBefore(param.getEndTime()) || effectiveBeginTime.isEqual(param.getEndTime())) {
                        return true;
                    }
                } else {
                    // 租赁合同  时间判判断
                    if (!(effectiveBeginTime.isAfter(param.getEndTime()) || param.getBeginTime().isAfter(effectiveEndTime))) {
                        return true;
                    }
                }
            }
            //  销售合同 房间被租赁到期在销售合同
        } else {
            for (ContractInfoResultDto c : contractInfoResultDtos) {
                Integer contractType = c.getType();
                // 销售合同存在 就不允许添加了
                if (ContractTypeEnum.sell.getCode().equals(contractType)) {
                    return true;
                } else {
                    // 租赁合同   到期在签订日期之前
                    LocalDate effectiveEndTime = c.getEffectiveEndTime();
                    if (!effectiveEndTime.isBefore(param.getBeginTime())) {
                        return true;
                    }
                }
            }
        }
        return false;
    }


}